﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace XEnamel
{
	public class Evaluator
	{
		#region Variables

		private IScopeManager _scope;

		#endregion

		#region Constructors

		public Evaluator(IScopeManager scope)
		{
			_scope = scope;
		}

		#endregion

		#region Methods

		public LabelTarget EvaluateLabel(string text)
		{
			if ((text.First() != '{') && (text.Last() != '}'))
			{
				throw new ArgumentException("Text is not an inline expression.", "text");
			}
			text = text.Substring(1, text.Length - 2);
			return _scope.VisitLabelTarget(text);
		}

		public IEnumerable<Expression> EvaluateList(string text)
		{
			return text.SplitEx().Select(x => Evaluate(x));
		}

		public Expression Evaluate(string text)
		{
			if ((text.First() != '{') && (text.Last() != '}'))
			{
				throw new ArgumentException("Text is not an inline expression.", "text");
			}
			text = text.Substring(1, text.Length - 2);
			return InnerEvaluate(text);
		}

		private Expression InnerEvaluate(string text)
		{
			return LambdaParser.Parse(text, _scope);
		}

		#endregion
	}
}